package com.feature50.makeover;

import com.feature50.makeover.utils.Platform;

import javax.swing.*;
import java.awt.*;

public class CircleLabel extends JComponent {
    private String text;
    private Color borderColor;

    public CircleLabel() {
        init();
    }

    public CircleLabel(String text) {
        this.text = text;
        init();
    }

    private void init() {
        setOpaque(false);
        setBackground(Color.BLACK);
        setForeground(Color.WHITE);
        setFont(new Font("Arial", Font.PLAIN, 14));
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Color getBorderColor() {
        return borderColor;
    }

    public void setBorderColor(Color borderColor) {
        this.borderColor = borderColor;
    }

    public Dimension getPreferredSize() {
        Graphics2D g2d = (Graphics2D) getGraphics().create();

        int width = (int) g2d.getFontMetrics().getStringBounds(text, g2d).getWidth();
        int height = g2d.getFontMetrics().getAscent();

        int size = Math.max(width, height) + 6;
        if (size % 2 == 0) size++;

        Dimension d = new Dimension(size, size);
        return d;
    }

    public Dimension getMinimumSize() {
        return getPreferredSize();
    }

    public Dimension getMaximumSize() {
        return getPreferredSize();
    }

    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create();

        int w = getWidth() - 1;
        int h = getHeight() - 1;

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(getBackground());
        g2d.fillOval(0, 0, w, h);

        if (borderColor != null) {
            g2d.setColor(borderColor);
            g2d.drawOval(0, 0, w, h);
        }

        g2d.setFont(getFont());
        Platform.setAntialiasing(g2d, getFont());
        int width = (int) g2d.getFontMetrics().getStringBounds(text, g2d).getWidth();
        int height = g2d.getFontMetrics().getAscent();

        int y = (h / 2) + (height / 2);
        int x = (w / 2) - (width / 2);

        // fudge factor
        y -= 1;
        x += 1;

        g2d.setColor(getForeground());
        g2d.drawString(text, x, y);

        g2d.dispose();
    }
}
